/**
 * 
 * author:zhangjlt
 * date:2016年9月2日3:18:42
 */
(function(){
	var idArray = new Array;
	var choose = {
		/**
		 *显示已经选择的项目
		 */
		showSelectedRow:function(){
			var productId = window.sessionStorage.productIds;
			var productName = window.sessionStorage.productNames;
			if (productId != "undefined" && productId) {
				idArray = productId.split(",");
			}	
			 //显示已选择项目
			 if(idArray != undefined && idArray !=""){
				 var uidArray=productId.split(",");
				 var unameArray=productName.split(",");
				 var but_html="";
				 for(var i=0;i<idArray.length;i++){
					 var html ='<button class ="choosedProductBtn" id ="choosedBtn'+uidArray[i]+'" pkid="'+uidArray[i]+'" product_name="'+unameArray[i]+'">'+unameArray[i]+'<span class="glyphicon glyphicon-remove"></span></button>';
						$("#choosedProductBtns").append(html);
				 }
				 $(".choosedProductBtn").unbind().on("click", function () {
						$(this).remove();
						//var id = $(this).attr("id");
						var checkid = $(this).attr("pkid");//id.substr(10,id.length-10);
						$("#chooseCheckbox"+checkid).prop({"checked":false});
						var pkid = $(this).attr("pkid");
						var j = new Number;
						for (var i=0; i < idArray.length; i++) {
						  if (idArray[i] == pkid) {
						  	j = i;
						  	break;
						  };
						};
						if (j !=NaN) {
							idArray.splice(j,1);
						};
				 });
		     }
		},
		//事件绑定
		bindEvent :function(){
			var index = parent.layer.getFrameIndex(window.name); 
			// 确定按钮
			
			$("#submit-product").unbind().on("click", function () {
				var products ={
					productIds: "",
					productNames:"",	
				};
				$("#choosedProductBtns").find('Button').each(function(index) {
					products.productIds +=$(this).attr("pkid")+",";
					products.productNames +=$(this).attr("product_name")+",";
				});
				products.productIds = products.productIds.substring(0,products.productIds.length-1);
			    products.productNames = products.productNames.substring(0,products.productNames.length-1);
				parent.$("#kmProductInput").val(products.productNames);
			    parent.$("#kmProductInput").text(products.productIds);
			    var layerIndex = window.sessionStorage.layerIndex;
			    if (layerIndex) {
			    	var obj = parent.document.getElementById('layui-layer-iframe' + layerIndex).contentWindow.document.getElementById('key_product');
			    	if (obj) {
			    		obj.value =products.productNames;
			    	};
			    	var obj2 = parent.document.getElementById('layui-layer-iframe' + layerIndex).contentWindow.document.getElementById('kmProductInputLayer');
			        if(obj2){
			        	obj2.value =products.productNames;
			        }
			      //  parent.document.getElementById('layui-layer-iframe' + layerIndex).contentWindow.document.getElementById('key_product').text =products.productIds;
			    };
			    window.sessionStorage.key_productId = products.productIds;
				parent.layer.close(index);
			});
			// 取消按钮
			$("#cancle-product").unbind().on("click", function () {
				parent.layer.close(index);
			});
			//搜索按钮
			$("#select-product-search-btn").unbind().on("click", function () {
				
			    choose.queryShellProductRequest($("#select-product-search-input").val());
			});	
		},	
		loadData:function(){
			var name = "";
			choose.queryShellProductRequest(name);
		},
		queryShellProductRequest:function(name){
			common.currentPage = 1;
			var functionParam = {
                "pk_user": window.localStorage.userid,
                "name": name,
                "pageSize":common.pageSize,
				"pageNum":common.currentPage,

            };
			//调用ajax
			var ajaxUrl = "/shellProduct/pageQuery";
			//转圈提示
			common.showLoading();
			common.interfaceAjaxFunction(ajaxUrl,functionParam,choose.queryShellProductSuccess,true);
		},
		 // 
		 /**
         * 查询接口回调
         */
        queryShellProductSuccess: function (res) {
            common.hideLoading();
            //console.log("产品关键字维护查询接口返回数据: ", JSON.stringify(res));
            if (res.status != 0) {
                layer.msg(res.message);
                return;
            } else {
                //更新UI
	    		//加载设置后的主页面
            	choose.updateUI(res);
	    		
            }
        },
        /**
         * 更新UI
         */
        updateUI: function (result) {
            var html = "";
            var dataArray = result["data"];
            if(dataArray.length > 0){
            	for (var i = 0; i < dataArray.length; i++) {
                    var dic = dataArray[i];
                    var product_name = dic["product_name"];
                    var pkid = dic["pk_product"];
                    html += '<tr ><th class="col-md-1" ><input class="chooseCheckbox" id ="chooseCheckbox'+pkid+'" type="checkbox" pkid="'+pkid+'" product_name="'+product_name+'"/></th>'
                           +'<td >'+product_name+'</td></tr>';
                }
                //刷新表格
                $("#chooseProductTbody").html(html);
            }else{
    			$("#chooseProductTbody").empty();
    			//加载设置页面
    			$("#chooseProductTbody").append("<tr><td colspan='2'>暂无产品数据</td></tr>");
    		}
            $("#chooseProductTbody tr").unbind().on("click",function(){
			   if($(this).find(".chooseCheckbox").prop("checked")){
			   	    var obj = $(this).find(".chooseCheckbox");
			   	    obj.prop("checked", false);
                    var id=obj.attr("id");
                    id = id.substring(14,id.length);//真正的id
            		$("#choosedBtn"+id).remove();  
            		for (var i=0; i < idArray.length; i++) {
						  if (idArray[i] == id) {
						  	j = i;
						  	break;
						  };
						};
					if (j !=NaN) {
						idArray.splice(j,1);
					};
        		}else{
        			var obj = $(this).find(".chooseCheckbox");
        			obj.prop("checked", true);
            		var pkid = obj.attr("pkid");
	            	var product_name =obj.attr("product_name");
	            	var id = obj.attr("id");
	            	var html ='<button class ="choosedProductBtn" id ="choosedBtn'+pkid+'" pkid="'+pkid+'" product_name="'+product_name+'">'+product_name+'<span class="glyphicon glyphicon-remove"></span></button>';
					$("#choosedProductBtns").append(html);
					idArray.push(pkid);
					$(".choosedProductBtn").unbind().on("click", function () {
						$(this).remove();
						//var id = $(this).attr("id");
						var pkid = $(this).attr("pkid");//id.substr(10,id.length-10);
						$("#chooseCheckbox"+pkid).prop({"checked":false});
						var j = new Number;
						for (var i=0; i < idArray.length; i++) {
						  if (idArray[i] == pkid) {
						  	j = i;
						  	break;
						  };
						};
						if (j !=NaN) {
							idArray.splice(j,1);
						};
					});

            	}
			});
            $(".chooseCheckbox").unbind().on("click", function () {
            	if($(this).prop("checked")){
            		$(this).prop("checked",false);
				
            	}else{
            		$(this).prop("checked",true);
            	}
            	
			});
			
			if (idArray.length>0) {
				
				$(".chooseCheckbox").each(function(index) {
					
					for (var i=0; i < idArray.length; i++) {
						if (idArray[i] ==$(this).attr("pkid")) {
							$(this).prop({"checked":true});
							var alreadyhad = false;
							$(".choosedProductBtn").each(function(index) {
							     if($(this).attr("pkid") == idArray[i]){
							     	alreadyhad = true;
							     }
							});
							if (alreadyhad) {
								
							}else{
								var pkid = $(this).attr("pkid");
				            	var product_name =$(this).attr("product_name");
				            	var id = $(this).attr("id");
				            	var html ='<button class ="choosedProductBtn" id ="choosedBtn'+id+'" pkid="'+pkid+'" product_name="'+product_name+'">'+product_name+'<span class="glyphicon glyphicon-remove"></span></button>';
								$("#choosedProductBtns").append(html);
								idArray.push(pkid);
								$(".choosedProductBtn").unbind().on("click", function () {
									$(this).remove();
									//var id = $(this).attr("id");
									var pkid = $(this).attr("pkid");
									$("#chooseCheckbox"+pkid).prop({"checked":false});
									var j = new Number;
									for (var i=0; i < idArray.length; i++) {
									  if (idArray[i] == pkid) {
									  	j = i;
									  };
									};
									if (j !=NaN) {
										idArray.splice(j,1);
									};										
								});
							}
							
						}
					};
				});
			};
            //产生分页结构
            common.getPageDivide(result.count, "pagernav",choose.updateList);
        },
        updateList: function () {
            //转圈
            common.showLoading();
            var url = "/shellProduct/pageQuery";
            var functionParam = {
                "pk_user": window.localStorage.userid,
                "pageSize": common.pageSize,
                "pageNum": common.currentPage,
                "name": $("#select-product-search-input").val()
            };
            common.interfaceAjaxFunction(url, functionParam, choose.queryShellProductSuccess, true);
       }
	};
	$(document).ready(function(){
		choose.showSelectedRow();
		choose.bindEvent();
		choose.loadData();
	});
})();